const Mock = require('mockjs')
const { param2Obj } = require('./utils')

var fs = require('fs')
var path = require('path')

function getJsFile(filePath, uplevel = './modules') {
  let flist = []
  try {
    let res = fs.readdirSync(filePath)
    res.forEach((fname) => {
      let _path = path.join(filePath, fname)
      let stats = fs.statSync(_path)
      let isFile = stats.isFile()
      if (isFile && _path.substr(-3) == '.js') flist.push(uplevel + '/' + fname)
      let isDir = stats.isDirectory()
      if (isDir) flist = [...flist, ...getJsFile(_path, uplevel + '/' + fname)]
    })
    return flist
  } catch (e) {
    console.log('getJsFile > error:', e)
    return []
  }
}

const modulesPath = path.join(__dirname, 'modules')
console.log('\nmock modules Path:', modulesPath)
let flist = getJsFile(path.join(__dirname, 'modules'))

// console.log('flist', flist)
let mocks = []
for (let x of flist) {
  console.log('import mock modules:', x)
  let mock = require(x)
  mocks = [...mocks, ...mock]
}

function mockXHR() {
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function () {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function (options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url),
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

module.exports = {
  mocks,
  mockXHR,
}
